<template>
  <div class="effectTimeWapper">
    <a-form-model
      ref="effectForm"
      :model="selectForm"
      :label-col="{ span: 0 }"
      :wrapper-col="{ span: 24 }"
      :rules="rules"
    >
      <a-form-model-item label="" prop="effectTime">
        <a-select
          class="customerSelect"
          :placeholder="$t('aclSingerConfNbrRgos.select')"
          v-model="selectForm.effectTime"
          option-label-prop="label"
        >
          <div slot="dropdownRender" slot-scope="menu">
            <div class="contentwapper">
              <v-nodes :vnodes="menu" />
            </div>
            <div
              class="customAdd"
              @mousedown="(e) => e.preventDefault()"
              @click="addCustomTime"
            >
              <a-icon type="plus" />
              {{ $t('aclSingerConfNbrRgos.define') }}
            </div>
          </div>
          <a-select-option
            v-for="it in timeRangeList"
            :key="it.rangeName"
            :label="it.description"
            :value="it.rangeName"
          >
            <div class="selectOptionWapper">
              <div class="valInfo">
                {{ it.description }}
                <span class="timeInfo" :title="renderTimeInfo(it)">{{
                  renderTimeInfo(it)
                }}</span>
              </div>
              <div class="operate" v-if="it.type != 'system'">
                <a-space>
                  <a-icon
                    type="edit"
                    class="opreateIcon"
                    @click.stop="editTime(it.rangeName)"
                    style="color: #2b6afd"
                  />
                  <a-icon
                    type="delete"
                    class="opreateIcon"
                    @click.stop="delTime(it.rangeName)"
                    style="color: #8c8c8c"
                  />
                </a-space>
              </div>
            </div>
          </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
    <rj-modal
      :visible="true"
      :title="$t('flowControl.customTimeQuantum')"
      :maskClosable="false"
      :keyboard="false"
      @cancel="close"
      @ok="ok"
      width="620px"
      v-if="modalVisible"
    >
      <a-form :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <!-- 备注 -->
        <a-form-item :label="$t('wirelessConfig.name')">
          <a-input
            :class="['inputStyle']"
            :placeholder="$t('flowControl.customTimeQuantum1')"
            autocomplete="off"
            :disabled="timeRangeOperate == 'edit'"
            v-decorator="[
              'rangeName',
              {
                initialValue: remark,
                rules: [
                  {
                    validator: checkRangeName,
                  },
                ],
              },
            ]"
          />
        </a-form-item>
        <!-- 时段 -->
        <div class="formInlineWapper">
          <span
            class="ant-col ant-col-3 ant-form-item-label mgBt24"
            style="color: rgba(0, 0, 0, 0.65)"
            >{{ $t('flowControl.timeQuantum') }}</span
          >
          <div
            class="ant-col ant-col-20 ant-form-item-control-wrapper lineWapper"
          >
            <div
              class="timeLineItem"
              v-for="(item, index) in rangeList"
              :key="item.ids"
            >
              <a-form-item label="">
                <a-select
                  style="width: 225px; margin-right: 10px"
                  :placeholder="$t('aclSingerConfNbrRgos.select')"
                  mode="multiple"
                  :maxTagPlaceholder="
                    () => {
                      return '...';
                    }
                  "
                  :maxTagCount="2"
                  v-decorator="[
                    `week_${item.ids}`,
                    {
                      initialValue: item.period,
                      rules: [
                        {
                          validator: checkWeek,
                        },
                      ],
                    },
                  ]"
                >
                  <a-select-option
                    v-for="it in getWeekList()"
                    :key="it.value"
                    :value="it.value"
                  >
                    {{ it.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="">
                <a-time-picker
                  format="HH:mm"
                  :placeholder="$t('aclSingerConfNbrRgos.timebegin')"
                  class="timeSelect"
                  style="margin-right: 10px"
                  v-decorator="[
                    `starttime_${item.ids}`,
                    {
                      initialValue: item.start
                        ? moment(item.start, 'HH:mm')
                        : null,
                      rules: [
                        {
                          validator: checkStartTime,
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
              <a-form-item label="">
                <a-time-picker
                  format="HH:mm"
                  :placeholder="$t('aclSingerConfNbrRgos.ending')"
                  class="timeSelect"
                  v-decorator="[
                    `endtime_${item.ids}`,
                    {
                      initialValue: item.end ? moment(item.end, 'HH:mm') : null,
                      rules: [
                        {
                          validator: checkEndTime,
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
              <a-space class="operateBtnWapper">
                <a-icon
                  type="plus"
                  class="operateIcon"
                  style="color: #2b6afd"
                  v-if="index == 0"
                  @click="addRange"
                />
                <a-icon
                  type="delete"
                  class="operateIcon"
                  style="color: #8c8c8c"
                  @click="removeRange(item.ids)"
                  v-else
                />
              </a-space>
            </div>
          </div>
        </div>
      </a-form>
    </rj-modal>
  </div>
</template>
<script>
import { maccApi, requestHttp } from '@utils/index';
import { RjModal } from '@components';
import moment from 'moment';
export default {
  name: 'EffectTime',
  props: {
    operate: {
      type: String,
      default: () => {
        return 'Add';
      },
    },
    deviceInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    curEffectTime: {
      type: String,
    },
    // tRangeList: {
    //   type: Array,
    //   default: () => {
    //     return [];
    //   },
    // },
  },

  data() {
    return {
      selectForm: {
        effectTime: undefined,
      },
      rules: {
        // effectTime: [{ validator: this.checkEffectTime, trigger: 'change' }],
      },
      modalVisible: false,
      // timeRangeList: lodash.cloneDeep(this.tRangeList),
      timeRangeList: [],
      weekDayObj: {},
      form: this.$form.createForm(this, {
        name: 'customTimForm',
      }),
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
      rangeList: [
        {
          ids: 1,
          end: null,
          period: [],
          start: null,
        },
      ],
      remark: '',
      timeRangeOperate: 'add',
    };
  },

  components: {
    'rj-modal': RjModal,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },

  computed: {
    isRgos() {
      return ['GATEWAY', 'SWITCH'].indexOf(this.deviceInfo.productType) != -1;
    },
    sn() {
      return this.deviceInfo.serialNumber;
    },
  },

  async mounted() {
    await this.getTimeRangeData();
    await this.getWeekDay();
    if (this.operate == 'Edit') {
      await this.editRender();
    }
  },

  watch: {},

  methods: {
    moment,
    //获取时间对象列表
    async getTimeRangeData() {
      const {
        code,
        msg = this.$t('flowControl.getFail2'),
        list = [],
      } = await requestHttp({
        api: `${maccApi.OPERATE_FLOWCTRL_TIMER_RANGER.replace(
          '{sn}',
          this.sn
        )}`,
        method: 'GET',
      });

      if (code != 0) {
        this.$message.error(msg);
        return;
      }

      this.timeRangeList = list.filter((item) => {
        return item.type != 'auto';
      });
    },
    //获取网关星期列表
    async getWeekDay() {
      const {
        code,
        msg = this.$t('flowControl.getFail'),
        data = {},
      } = await requestHttp({
        api: maccApi.GET_WEEKDAY.replace('{sn}', this.sn),
        method: 'GET',
      });
      if (code != 0) {
        this.$message.error(msg);
        return;
      }
      this.weekDayObj = data;
    },

    async editRender() {
      this.selectForm = {
        effectTime: this.curEffectTime,
      };
    },

    //时间对象转换
    async transformRangDate(trSlots) {
      const {
        code,
        msg = this.$t('flowControl.timeTranFail'),
        list = [],
      } = await requestHttp({
        api: maccApi.COVER_TIMERANGE,
        method: 'POST',
        params: trSlots,
      });

      if (code != 0) {
        this.$message.error(msg);
        return;
      }

      return list;
    },

    //添加时间段
    addRange() {
      this.rangeList.push({
        ids: new Date().getTime(),
        end: null,
        period: [],
        start: null,
      });
    },

    //删除时间段
    removeRange(ids) {
      this.rangeList = this.rangeList.filter((item) => {
        return item.ids != ids;
      });
    },

    //获取星期数组
    getWeekList() {
      const weekData = [];
      Object.keys(this.weekDayObj).forEach((item) => {
        weekData.push({
          value: item,
          label: this.weekDayObj[item],
        });
      });
      return weekData.sort();
    },

    //点击添加自定义时间
    addCustomTime() {
      console.log('1111');
      this.modalVisible = true;
      this.timeRangeOperate = 'add';
    },

    //渲染时间段详情
    renderTimeInfo(info) {
      const { periods } = info;
      let rangeStr = '';
      if (periods && periods.length > 0) {
        const copyPeriods = [...periods];
        copyPeriods.sort().forEach((item) => {
          const { start, end, period = [] } = item;
          if (
            this.isRgos &&
            period.length == 7 &&
            start == '00:00' &&
            end == '23:59'
          ) {
            return;
          }

          period.forEach((item, index) => {
            rangeStr += `${this.weekDayObj[item] || ''}${
              index < period.length - 1 ? ',' : ''
            }`;
          });
          rangeStr += `:${start}-${end}`;
        });
      }

      return rangeStr;
    },

    //校验
    checkEffectTime(rule, value, callback) {
      if (!value || value === '') {
        callback(new Error(this.$t('flowControl.pleaseEnter')));
      } else {
        callback();
      }
    },

    //校验备注
    checkRangeName(rule, value, callback) {
      if (value == undefined || value == '') {
        callback(new Error(this.$t('flowControl.pleaseWrite')));
      }
      var strByteLen = value.replace(/[^\x00-\xff]/g, '|||').length;
      if (strByteLen > 64) {
        callback(new Error(this.$t('flowControl.tip22')));
      }
      callback();
    },

    //校验星期
    checkWeek(rule, value, callback) {
      if (value.length == 0) {
        callback(new Error(this.$t('aclSingerConfNbrRgos.selectdat')));
      }
      callback();
    },

    //校验开始时间
    checkStartTime(rule, value, callback) {
      if (value == null) {
        callback(new Error(this.$t('aclSingerConfNbrRgos.begintime')));
      }

      const { field } = rule;
      const ids = field.split('_')[1];
      const endTime = this.form.getFieldValue(`endtime_${ids}`);
      if (endTime && endTime < value) {
        callback(new Error(this.$t('flowControl.tip23')));
      }

      callback();
    },

    //校验结束时间
    checkEndTime(rule, value, callback) {
      if (value == null) {
        callback(new Error(this.$t('aclSingerConfNbrRgos.selectending')));
      }

      const { field } = rule;
      const ids = field.split('_')[1];
      const startTime = this.form.getFieldValue(`starttime_${ids}`);
      if (startTime && startTime > value) {
        callback(new Error(this.$t('flowControl.tip24')));
      }
      callback();
    },

    //修改时间段选项
    editTime(name) {
      console.log('name', name);
      const rangeInfo = this.timeRangeList.find((item) => {
        return item.rangeName == name;
      });

      if (!rangeInfo) return;

      const { periods, rangeName } = rangeInfo;

      this.rangeList = periods.map((item, index) => {
        item.ids = index;
        return item;
      });
      console.log('this.rangeList111', this.rangeList);
      this.remark = rangeName;
      this.modalVisible = true;
      this.timeRangeOperate = 'edit';
    },

    //删除时间选项
    async delTime(name) {
      console.log('name', name);
      RjModal.confirm({
        title: this.$t('ipTerminalMana.tip'),
        content: this.$t('aclSingerConfNbrRgos.deletcomfirm', [name]),
        okText: this.$t('deviceDetail.comfirmOk'),
        cancelText: this.$t('intelligentterminal.cancel'),
        onOk: () => {
          this.timeRangeList = this.timeRangeList.filter((item) => {
            return item.rangeName != name;
          });

          if (this.selectForm.effectTime == name) {
            //删除的项是当前选中的，重置下拉框
            this.selectForm = {
              effectTime: undefined,
            };
          }
        },
      });
    },

    close() {
      this.modalVisible = false;
      this.showForm = false;
      this.rangeList = [
        {
          ids: 1,
          end: null,
          period: [],
          start: null,
        },
      ];
      this.$refs.effectForm.resetFields();
      this.remark = '';
    },

    async ok() {
      this.form.validateFieldsAndScroll(async (err, values) => {
        console.log('values111', values);
        if (!err) {
          const { rangeName } = values;
          const periods = [];
          this.rangeList.forEach((item) => {
            const { ids } = item;
            const period = values[`week_${ids}`];
            const start = values[`starttime_${ids}`].format('HH:mm');
            const end = values[`endtime_${ids}`].format('HH:mm');
            periods.push({
              period,
              start,
              end,
            });
          });
          console.log('data11111', { rangeName, periods });
          const timeArr = [...this.timeRangeList];
          if (this.timeRangeOperate == 'edit') {
            timeArr.forEach((item) => {
              if (item.rangeName == rangeName) {
                item.periods = periods;
              }
            });
          } else {
            timeArr.push({
              description: rangeName,
              rangeName,
              type: 'user',
              user: '0',
              periods,
            });
          }
          this.timeRangeList = timeArr;
          this.modalVisible = false;
        }
      });
    },

    getEffectTimeVal() {
      return new Promise((resolve) => {
        this.$refs.effectForm.validate((valid) => {
          if (valid) {
            resolve({
              success: true,
              data: {
                effectTime: this.selectForm.effectTime,
                timeRangeList: this.timeRangeList,
              },
            });
          } else {
            resolve({
              success: false,
            });
          }
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.effectTimeWapper {
  width: 100%;
  box-sizing: border-box;
}
.customerSelect {
  width: 100%;
  box-sizing: border-box;
}
.customAdd {
  padding: 8px;
  cursor: pointer;
  margin: 4px 0;
  padding-top: 15px;
  border-top: 1px solid #ececec;
}
.selectOptionWapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .valInfo {
    margin-right: 10px;
    width: calc(100% - 60px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap; //表示强制换行显示
    display: inline-block;
  }
  .operate {
    display: none;
  }
  .opreateIcon {
    font-size: 16px;
  }
  &:hover {
    .operate {
      display: inline-block;
    }
  }
  .timeInfo {
    margin-left: 10px;
    color: rgba(0, 0, 0, 0.45);
    text-shadow: 0px 2px 8px rgba(0, 0, 0, 0.1);
    font-size: 12px;
  }
}
.formInlineWapper {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
}

.timeLineItem {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /deep/ .ant-col {
    width: 100%;
    box-sizing: border-box;
  }
}

/deep/.lineWapper {
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  justify-content: flex-start;
  .ant-form-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .wapperConfLine {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .ant-form-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      .ant-col {
        width: 100%;
        box-sizing: border-box;
      }
    }
  }
}
.mgBt24 {
  margin-bottom: 24px;
}
.separate {
  margin: 0px 5px 24px 5px;
}
.operateIcon {
  margin-left: 10px;
}
.operateIcon {
  font-size: 20px;
  padding: 5px;
  cursor: pointer;
}
.operateBtnWapper {
  margin-bottom: 24px;
}
.timeSelect {
  width: 115px;
}
</style>
